package com.yxd.processor;

import com.yxd.bootstrap.Constants;
import com.yxd.connector.http.HttpRequest;
import com.yxd.connector.http.HttpResponse;
import com.yxd.contract.HttpProcessor;
import com.yxd.server.RequestFacade;
import com.yxd.server.ResponseFacade;

import javax.servlet.Servlet;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Created by Administrator on 2016/6/15.
 */
public class ServletProcessor extends HttpProcessor {

    @Override
    public void processor(HttpRequest request, HttpResponse response) {
        String uri = request.getRequestURI();
        int pos = uri.lastIndexOf("/");
        if (pos != -1) {
            String servletName = uri.substring(pos + 1);
            URLClassLoader loader = null;
            try {
                File file = new File(Constants.WRB_ROOT);
                URL[] urls = {new URL("file", null, file.getCanonicalPath() + File.separator + "webInfo" + File.separator)};
                loader = new URLClassLoader(urls);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Class clazz = loader.loadClass(servletName);
                Servlet obj = (Servlet) clazz.newInstance();
                obj.service(request, response);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                try {
                    response.getWriter().println("class not found");
                    response.getWriter().close();
                } catch (Exception ex) {
                    e.printStackTrace();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
